package com.sonix.app;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.sonix.base.BaseActivity;
import com.sonix.oidbluetooth.BoardActivity;
import com.sonix.oidbluetooth.MainActivity;
import com.sonix.util.CrashHandler;
import com.sonix.util.Events;
import com.sonix.util.MultiLanguageUtils;
import com.tqltech.tqlpencomm.BLEException;
import com.tqltech.tqlpencomm.PenCommAgent;
import com.tqltech.tqlpencomm.bean.Dot;
import com.tqltech.tqlpencomm.bean.ElementCode;
import com.tqltech.tqlpencomm.bean.PenStatus;
import com.tqltech.tqlpencomm.listener.TQLPenSignal;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by wangyong on 7/4/17.
 */
public class App extends Application {
    private static final String TAG = "App";
    public static String SP_LANGUAGE = "language";
    public static String SP_COUNTRY = "country";
    public static String mPenName = "NAME";
    public static String mFirmWare = "BT";
    public static String mMCUFirmWare = "MCU";
    public static String mCustomerID = "0000";
    public static String mBTMac = "00:00:00:00:00:00";
    public static int mBattery = 100;
    public static boolean mCharging = false;
    public static int mUsedMem = 0;
    public static boolean mBeep = true;
    public static boolean mPowerOnMode = true;
    public static boolean mEnableLED = false;
    public static int mPowerOffTime = 20;
    public static long mTimer = 0; // 2010-01-01 00:00:00
    public static int mPenSens = 0;
    public static int mTwentyPressure = 0;
    public static int mThreeHundredPressure = 0;

    public static String tmp_mPenName;
    public static boolean tmp_mBeep = true;
    public static boolean tmp_mPowerOnMode = true;
    public static boolean tmp_mEnableLED = false;
    public static int tmp_mPowerOffTime;
    public static int tmp_mPenSens;
    public static long tmp_mTimer;

    public static int mUsbEnable;

    public static int mPenType = -1;

    public static boolean isDrawStoke = true;
    public static boolean isUsbOpen = false;
    private static App instance;
    public static String mDeviceName;
    private String mDeviceAddress;
    private String mDeviceBattery;
    private int mDeviceType;
    private boolean mDeviceConnected;
    //点读码计时
    private long tmpTime;
    private ArrayList<BaseActivity> activities = new ArrayList<>();
    private Dot curDot;

    public static App getInstance() {
        return instance;
    }

    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    /**
     * 获取本地软件版本号
     */
    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
            Log.d("TAG", "本软件的版本号。。" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
            Log.d("TAG", "本软件的版本号。。" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * 判断版本是否为Debug
     *
     * @param ctx
     * @return
     */
    public static boolean isDebuggable(Context ctx) {
        boolean debuggable = false;
        PackageManager pm = ctx.getApplicationContext().getPackageManager();
        try {
            ApplicationInfo appinfo = pm.getApplicationInfo(ctx.getPackageName(), 0);
            debuggable = (0 != (appinfo.flags & ApplicationInfo.FLAG_DEBUGGABLE));
        } catch (PackageManager.NameNotFoundException e) {
            /*debuggable variable will remain false*/
        }
        return debuggable;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        //多语言设置
        registerActivityLifecycleCallbacks(MultiLanguageUtils.callbacks);

        closeAndroidPDialog();
        // 以下用来捕获程序崩溃异常
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());

    }

    @Override
    protected void attachBaseContext(Context base) {
        //系统语言等设置发生改变时会调用此方法，需要要重置app语言
        super.attachBaseContext(MultiLanguageUtils.attachBaseContext(base));
    }

    /**
     * 关闭在Android P上提醒弹窗
     */
    private void closeAndroidPDialog() {
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void activityCreate(BaseActivity activity) {
        activities.add(activity);
    }

    public void activityResume(BaseActivity activity) {
        activities.remove(activity);
        activities.add(activity);
    }

    public void activityDestroy(BaseActivity activity) {
        activities.remove(activity);
    }

    public final Dot getCurDot() {
        return curDot;
    }

    public final void setCurDot(Dot dot) {
        curDot = dot;
    }

    public final String getDeviceName() {
        return mDeviceName;
    }

    public final void setDeviceName(String deviceName) {
        mDeviceName = deviceName;
    }

    public final void setDeviceAddress(String deviceAddress) {
        mDeviceAddress = deviceAddress;
    }

    public final String getDeviceAddress() {
        return mDeviceAddress;
    }

    public final String getDeviceBattery() {
        return mDeviceBattery;
    }

    public final int getDeviceType() {
        return mDeviceType;
    }

    public final void setDeviceConnected(boolean deviceConnected) {
        mDeviceConnected = deviceConnected;
    }

    public boolean isDeviceConnected() {
        return mDeviceConnected;
    }
}
